angular.module('furion.controllers.security', [])

.controller 'GetPassCtrl', ($scope, RemoteSrv, Toast, $state, $ionicPopup, $ionicLoading, $rootScope, VcodeService, WizardHandler) ->
  $scope.vcode_reject_waiting = $rootScope.vcode_reject_waiting
  $scope.isLogin = furion.storage.isLogin()
  $scope.account =
    phone: furion.storage.account().phone
    vcode: ''
    password: ''
  $scope.canSubmit = false

  $scope.timeClick = false
  $scope.btnCodeHint = '发送验证码'
  $scope.interval = 0
  timer = null


  $scope.changeInput = ()->
    if $scope.account.phone && $scope.account.password && $scope.account.vcode
      $scope.canSubmit = true
    else
      $scope.canSubmit = false

#  countDown = ()->
#    $scope.$apply ()->
#      $scope.interval -= 1
#      if $scope.interval <= 0
#        $scope.timeClick = false
#        $scope.btnCodeHint = '发送验证码'
#        clearInterval(timer) if timer
#      else
#        $scope.btnCodeHint = "发送（#{$scope.interval}）"

  $scope.sendCode = ()->
    r = furion.utils.verifyPhone($scope.account.phone)
    if !r.result
      Toast.show r.data
      return

    $scope.$emit "loading:show"
    RemoteSrv.getValidationCode($scope.account.phone, 'reset_password').done( (resp) ->
      console.debug resp
      if resp.status.success
#        clearInterval(timer) if timer
#        $scope.timeClick = true
#        $scope.interval = resp.data.interval
#        $scope.btnCodeHint = "发送（#{$scope.interval}）"
#        timer = setInterval(countDown, 1000)
        VcodeService.setRejectWaiting('reset_password', resp.data.interval)
        $scope.vcode_reject_waiting = $rootScope.vcode_reject_waiting
        console.debug $scope.vcode_reject_waiting
        Toast.show resp.data.vcode, 'long' if resp.data.vcode # debug 模式下可以看到验证码
      else
        Toast.show resp.status.msg
    ).always ->
      $scope.$emit "loading:hide"

  $scope.doResetPassword = ()->
    r = furion.utils.verifyPhone($scope.account.phone)
    if !r.result
      Toast.show r.data
      return
    r = furion.utils.verifyPassword($scope.account.password)
    if !r.result
      Toast.show r.data
      return
    r = furion.utils.verifySmsCode($scope.account.vcode)
    if !r.result
      Toast.show r.data
      return

    RemoteSrv.resetPassword($scope.account).done (resp) ->
      if resp.status.success
        alertPopup = $ionicPopup.show
          title: '提示'
          template: '修改成功，请重新登陆'
          scope: $scope,
          buttons: [
            type: 'button-assertive'
            text: '确定'
            onTap: (e)->
              furion.storage.deleteAccount()
              $scope.$emit("modals:close", {modal_name: 'get_pass'})
              $state.go 'app.home'
              $scope.$emit("modals:open", {modal_name: 'signin'})
          ]
      else
        Toast.show resp.status.msg
  return
# .controller 'GetPassCtrl'

.controller 'PayPasswordCtrl', ($scope, RemoteSrv, WizardHandler, $ionicPopup, $state, Toast) ->
  curStep = 1
  $scope.newPwd = []
  $scope.newPwd2 = []

  $scope.$on '$ionicView.enter', (event)->
    $scope.account = furion.storage.account()
    curStep = 1
    $scope.newPwd = []
    $scope.newPwd2 = []

  $scope.pushPwd = (num)->
    pwd = null
    switch curStep
      when 1
        pwd = $scope.newPwd
      when 2
        pwd = $scope.newPwd2
    return if pwd.length > 5
    pwd.push num if pwd
    nextStep() if pwd && pwd.length > 5

  $scope.popPwd = ()->
    pwd = null
    switch curStep
      when 1
        pwd = $scope.newPwd
      when 2
        pwd = $scope.newPwd2
    pwd.pop() if pwd

  alertPop = (hint)->
    confirmPopup = $ionicPopup.alert
      title: "提示"
      template: hint
      okText: '确定'
    confirmPopup.then () ->
      $scope.newPwd = []
      $scope.newPwd2 = []
      curStep = 1
      WizardHandler.wizard().goTo(0)

  createPayPassword = ()->
    $scope.$emit "loading:show"
    RemoteSrv.createPayPwd($scope.newPwd.join('')).done( (resp)->
      if resp.status.success
        Toast.show "支付密码创建成功"
        furion.storage.updateAccount has_pay_pwd: true
        $scope.goBack()
      else
        alertPop("支付密码创建失败，请重试")
    ).always ->
      $scope.$emit "loading:hide"

  nextStep = ()->
    switch curStep
      when 1
        curStep += 1
        WizardHandler.wizard().next()
      when 2
        if $scope.newPwd.join("") != $scope.newPwd2.join("")
          alertPop("两次密码输入不匹配，请重新输入")
        else
          createPayPassword()

  return
# end of PayPasswordCtrl

# ChangePayPasswordCtrl
.controller 'ChangePayPasswordCtrl', ($scope, RemoteSrv, WizardHandler, $ionicPopup, $state, Toast) ->
  curStep = 1
  $scope.oldPwd = []
  $scope.newPwd = []
  $scope.newPwd2 = []

  $scope.$on '$ionicView.enter', (event)->
    curStep = 1
    $scope.oldPwd = []
    $scope.newPwd = []
    $scope.newPwd2 = []
    WizardHandler.wizard().goTo(0)

  $scope.pushPwd = (num)->
    pwd = null
    switch curStep
      when 1
        pwd = $scope.oldPwd
      when 2
        pwd = $scope.newPwd
      when 3
        pwd = $scope.newPwd2
    return if pwd.length > 5
    pwd.push num if pwd
    nextStep() if pwd && pwd.length > 5

  $scope.popPwd = ()->
    pwd = null
    switch curStep
      when 1
        pwd = $scope.oldPwd
      when 2
        pwd = $scope.newPwd
      when 3
        pwd = $scope.newPwd2
    pwd.pop() if pwd

  changePayPassword = ()->
    $scope.$emit "loading:show"
    RemoteSrv.changePayPwd($scope.oldPwd.join(''), $scope.newPwd.join('')).done( (resp)->
      if resp.status.success
        Toast.show "支付密码修改成功"
        $scope.goBack()
      else
        confirmPopup = $ionicPopup.confirm
          title: "提示"
          template: "支付密码重置失败，是否重试？"
          okText: '确定'
          cancelText: '取消'
        confirmPopup.then (res) ->
          if res
            $scope.oldPwd = []
            $scope.newPwd = []
            $scope.newPwd2 = []
            curStep = 1
            WizardHandler.wizard().goTo(0)
          else
            $scope.goBack()
    ).always ->
      $scope.$emit "loading:hide"

  nextStep = ()->
    switch curStep
      when 1
        $scope.$emit "loading:show"
        RemoteSrv.verifyPayPwd($scope.oldPwd.join("")).done( (resp)->
          if resp.data
            curStep += 1
            WizardHandler.wizard().next()
          else
            confirmPopup = $ionicPopup.confirm
              title: "提示"
              template: "支付密码错误，请重试"
              okText: '确定'
              cancelText: '忘记密码'
            confirmPopup.then (res) ->
              if res
                $scope.oldPwd = []
                curStep = 1
              else
                $state.go 'forget-pay-password'
        ).always ->
          $scope.$emit "loading:hide"
      when 2
        curStep += 1
        WizardHandler.wizard().next()
      when 3
        if $scope.newPwd.join("") != $scope.newPwd2.join("")
          confirmPopup = $ionicPopup.confirm
            title: "提示"
            template: "两次密码输入不匹配，是否重新输入？"
            okText: '确定'
            cancelText: '取消'
          confirmPopup.then (res) ->
            if res
              $scope.newPwd = []
              $scope.newPwd2 = []
              curStep = 2
              WizardHandler.wizard().previous()
            else # 取消
              $scope.goBack()
        else
          changePayPassword()

  return
# end of ChangePayPasswordCtrl

# ForgetPayPasswordCtrl
.controller 'ForgetPayPasswordCtrl', ($scope, $state, RemoteSrv, $ionicPopup, Toast, WizardHandler, VcodeService) ->
  $scope.isPhoneValidated = true
  # $scope.timeClick = false
  $scope.account =
    phone: furion.storage.account().phone
    password: ''
  $scope.btnCodeHint = '发送验证码'
  timer = null
  $scope.sendValidated = false

  $scope.$on '$ionicView.enter', (event)->
    $scope.account =
      phone: furion.storage.account().phone
      password: ''
    curStep = 1
    WizardHandler.wizard().goTo(0)

  $scope.$on "$destroy", (event)->
    clearInterval(timer) if timer

  $scope.canNextStep = ()->
    furion.utils.verifySmsCode($scope.account.vcode).result

  $scope.nextStep = ()->
    if curStep = 1
      $scope.$emit "loading:show"
      RemoteSrv.verifyVcode($scope.account.phone, 'reset_paypwd', $scope.account.vcode).done( (resp) ->
        if resp.status.success
          if resp.data
            curStep += 1
            WizardHandler.wizard().next()
            $scope.showPwdPad = true
          else
            $ionicPopup.alert
              title: '提示',
              template: '验证码错误',
              okText: '确定',
              okType: 'button-positive'
        else
          Toast.show resp.status.msg
      ).always ->
        $scope.$emit "loading:hide"

  $scope.pushPwd = (n)->
    if $scope.account.password.length < 6
      $scope.account.password = $scope.account.password.concat n
    if $scope.account.password.length == 6
      resetPassword()

  $scope.popPwd = ()->
    $scope.account.password = $scope.account.password.slice 0, $scope.account.password.length - 1

  # countDown = ()->
  #   $scope.$apply ()->
  #     $scope.forget_pay_or_login_password_interval -= 1
  #     if $scope.forget_pay_or_login_password_interval <= 0
  #       $scope.timeClick = false
  #       $scope.btnCodeHint = '发送验证码'
  #       clearInterval(timer) if timer
  #       $scope.phoneChange()
  #     else
  #       $scope.btnCodeHint = "再次发送(#{$scope.forget_pay_or_login_password_interval})"

  $scope.getCode = ()->
    RemoteSrv.getValidationCode($scope.account.phone, 'reset_paypwd').done (resp) ->
      console.debug resp
      if resp.status.success
        # clearInterval(timer) if timer
        $scope.isPhoneValidated = false
        # $scope.timeClick = true
        # $scope.forget_pay_or_login_password_interval = parseInt resp.data.interval
        # $scope.btnCodeHint = "再次发送(#{$scope.forget_pay_or_login_password_interval})"
        # timer = setInterval(countDown, 1000)
        VcodeService.setRejectWaiting('reset_paypwd', resp.data.interval)
        Toast.show resp.data.vcode, 'long' if resp.data.vcode # debug 模式下可以看到验证码
      else
        Toast.show resp.status.msg

  $scope.passwordChange = ()->
    if $scope.account.vcode && $scope.account.password
      $scope.sendValidated = true
    else
      $scope.sendValidated = false

  resetPassword = ()->
    r = furion.utils.verifySmsCode($scope.account.vcode)
    if !r.result
      Toast.show r.data
      return
    if !$scope.account.password.match /^\d{6}$/
      Toast.show '支付密码为6位数字组合'
      return

    $scope.$emit "loading:show"
    RemoteSrv.resetPayPassword($scope.account.vcode, $scope.account.password).done( (resp) ->
      if resp.status.success
        alertPopup = $ionicPopup.alert
          title: '提示'
          template: '修改成功'
          okType: 'button-positive'
          okText: '确定'
        alertPopup.then (res)->
          $scope.goBack()
      else
        Toast.show resp.status.msg
    ).always ->
      $scope.$emit "loading:hide"

  return
# end of ForgetPayPasswordCtrl

.controller 'NickNameCtrl', ($scope, RemoteSrv, Toast) ->
  $scope.account = furion.storage.account()

  $scope.$on '$ionicView.enter', (event)->
    $scope.account = furion.storage.account()
    $scope.nickname = $scope.account.base.vname

  $scope.setNickname = (nickname)->
    RemoteSrv.setNickname(nickname).done (resp)->
      furion.storage.updateAccount resp.data.account
      if resp.data.result
        Toast.show '修改昵称成功'
        $scope.goBack()
      else
        Toast.show '修改昵称失败，昵称长度只能为1～8位，且不能带有非法字符'
  return
# .controller 'NickNameCtrl'

.controller 'GestureSettingCtrl', ($scope, $cordovaDevice, RemoteSrv, $rootScope, $state, Toast, $ionicModal, $ionicHistory, GestureService, TouchidService) ->
  $scope.gesture = {}
  $scope.touchid =
    isSupport: TouchidService.isDeviceSupport()
    isEnabled: furion.storage.account().touchid_is_enabled

  if GestureService.isEnabled()
    $scope.gesture.isEnabled = true
  else
    $scope.gesture.isEnabled = false

  if furion.utils.isDevice()
    $scope.isDevice = true
  else
    $scope.isDevice = false

  if GestureService.getPattern()
    $scope.gesture_set = true
  else
    $scope.gesture_set = false

  $scope.gesturePassword = () ->
    url = window.location.href
    current_url = url[url.indexOf('#')..url.length-1]
    window.localStorage.setItem('rt-gesture_password_prev_url', current_url)
    $state.go 'gesture-password'

  $scope.toggleTouchid = () ->
    $scope.$emit "loading:show"
    RemoteSrv.setTouchid({touchid_enabled: $scope.touchid.isEnabled}).done (resp) ->
      if resp.status.success
        console.log('开启指纹密码成功')
        furion.storage.updateAccount resp.data.account
      else
        $scope.touchid.isEnabled = !$scope.touchid.isEnabled
        console.log('开启指纹密码失败,请稍后重试')
        Toast.show '开启指纹密码失败,请稍后重试'
    .always ()->
      $scope.$emit "loading:hide"

  $scope.toggleGesture = () ->
    if GestureService.isEnabled()
      console.log("toggle"+GestureService.isEnabled())

      GestureService.disable()
      $scope.gesture.isEnabled = false
    else
      console.log("toggle"+GestureService.isEnabled())
      GestureService.enable()
      $scope.gesture.isEnabled = true

    RemoteSrv.setGesture({gesture: GestureService.getPattern(), gesture_enabled: $scope.gesture.isEnabled}).done (resp) ->
      if resp.status.success
        console.log('向服务器保存手势成功')
        furion.storage.updateAccount {gesture_enabled: $scope.gesture.isEnabled}
      else
        GestureService.disable()
        $scope.gesture.isEnabled = false
        furion.storage.updateAccount {gesture_enabled: false}
        console.log('向服务器保存手势失败，请稍后重试')
        Toast.show '向服务器保存手势失败，请稍后重试'
    .always ->
        # $rootScope.$broadcast("loading:hide");
        # GestureService.setPattern(pattern)
        # $scope.pattern_set = true
        # Toast.show "手势密码设置完成"
        # $scope.lock.enable()
        # $scope.lock.reset()
        # $state.go('tab.asset')
  return
# .controller 'GestureSettingCtrl'

.controller 'GesturePasswordCtrl', ($scope, $cordovaDevice, RemoteSrv, $rootScope, $state, Toast, $ionicHistory, GestureService, $timeout) ->
  $scope.error = false
  $scope.not_in_limit = false
  $scope.account = {}
  $scope.preparing = true

  $timeout ()->
    $scope.preparing = false
  , 1000

  reset = ()->
    $scope.log_pattern = GestureService.getPattern()
    $scope.confirm = false
    $scope.reenter = false
    $scope.confirm_pattern = ""
    $scope.confirm_mismatch = false
    $scope.pattern_set = false
    $scope.loading = false

  $scope.goBack = () ->
    prev_url = window.localStorage.getItem('rt-gesture_password_prev_url')
    if !prev_url
      $state.go 'app.home'
      return false
    console.log 'gesture-password goBack'
    $ionicHistory.goBack()
    window.localStorage.removeItem('rt-gesture_password_prev_url')

  $scope.$on '$ionicView.enter', (event)->
    $scope.account = furion.storage.account()
    reset()
    $scope.lock = new PatternLock('#lockPattern',
      margin: document.documentElement.clientWidth / 18,
      radius: document.documentElement.clientWidth / 12,
      onDraw:(pattern)->
        if ($scope.log_pattern and not $scope.reenter and not $scope.confirm)
          gcp = GestureService.checkPattern(pattern)
          gcp.success((data) ->
            console.log("SUCCESS gesture check")
            $scope.error = false
            $scope.lock.reset()
            # GestureService.resetPattern()
            # $state.go('gesture')
            $scope.reenter = true
            reenter(pattern)
          ).error((data) ->
            console.log("failed gesture check")
            $scope.lock.error()
            $scope.error = true
            $scope.lock.reset()
            setTimeout ->
              $scope.$apply ->
                $scope.error = false
            , 800
          )
        else
          console.log("Going else:"+$scope.reenter)
          if $scope.confirm || GestureService.checkLimit(pattern)
            $scope.not_in_limit = false
            if !$scope.confirm
              $scope.reenter = !$scope.reenter
            reenter(pattern)
              # $scope.log_pattern = GestureService.getPattern()
              # $scope.$apply()
          else
            console.debug "not in limit"
            $scope.$apply ->
              $scope.not_in_limit = true
            $scope.lock.reset()
            setTimeout ->
              $scope.$apply ->
                $scope.not_in_limit = false
            , 800
    )# $scope.lock

  reenter = (pattern) ->
    if $scope.reenter and $scope.log_pattern
      console.log("init gesture reenter, confirm phase 0")
      $scope.lock.reset()
      # $scope.$apply()
      return
    if !$scope.confirm
      console.log("set gesture check, confirm phase 1")
      $scope.confirm = true
      $scope.reenter = false
      $scope.confirm_pattern = pattern
      $scope.$apply()
      $scope.lock.reset()
    else
      if pattern == $scope.confirm_pattern
        console.log("set gesture check phase 2: "+pattern)
        $rootScope.$broadcast("loading:show");
        $scope.lock.disable()
        $scope.loading = true
        $scope.$apply()
        RemoteSrv.setGesture({gesture: GestureService.encPattern(pattern), gesture_enabled: true}).done (resp) ->
          if resp.status.success
            console.log('向服务器保存手势成功')
          else
            console.log('向服务器保存手势失败，请稍后重试')
            # Toast.show '向服务器保存手势失败，请稍后重试'
        .always ->
          $rootScope.$broadcast("loading:hide");
          GestureService.setPattern(pattern)
          $scope.pattern_set = true
          Toast.show "手势密码设置完成"
          $scope.lock.enable()
          $scope.lock.reset()
          prev_url = window.localStorage.getItem('rt-gesture_password_prev_url')
          if prev_url
            window.location.assign prev_url
            window.localStorage.removeItem('rt-gesture_password_prev_url')
          else
            $state.go 'app.home'
      else
        reset()
        $scope.reenter = true
        $scope.confirm_mismatch = true
        console.log("set gesture check phase 2, doesn't match")
        console.log(pattern)
        $scope.lock.reset()
        $scope.$apply()
        console.log($scope.confirm_pattern)
  return

.controller 'GestureLoginCtrl', ($scope, RemoteSrv, $rootScope, $state, Toast, $ionicModal, GestureService) ->
  $scope.log_pattern = GestureService.getPattern()
  $scope.error = false

  # gesture-login can't go back!!!
  $scope.goBack = ()->
    false

  $scope.openGetPass = ()->
    $scope.$emit "modals:open", {modal_name: "get_pass"}

  $scope.resetGesture = () ->
    $scope.openModal()

  $scope.switchAccount = () ->
    $scope.$emit "modals:open", {modal_name: "signin", params: {state: 'gesture-login'}}

  $ionicModal.fromTemplateUrl('templates/accounts/reset-gesture.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then( (modal) ->
    $scope.modal = modal
  )

  $scope.openModal = ()->
    $scope.modal.show()

  $scope.goBack = ()->
    $scope.modal.hide()

  $scope.$on '$destroy', ()->
    $scope.modal.remove()

  $scope.account = {}

  $scope.changeInput = ()->
    if $scope.account.phone && $scope.account.password && $scope.account.password.length >= 6
      $scope.canSubmit = true
    else
      $scope.canSubmit = false

  $scope.account.phone = furion.storage.account().phone

  $scope.doReset = () ->
    params =
      username: $scope.account.phone
      password: $scope.account.password

    $rootScope.$broadcast("loading:show");
    RemoteSrv.resetGesture(params).done (resp) ->
      if resp.data.result
        GestureService.resetPattern()
        RemoteSrv.setGesture({gesture: GestureService.getPattern(), gesture_enabled: false}).done (resp) ->
          if resp.status.success
            console.log('向服务器保存手势成功')
          else
            console.log('向服务器保存手势失败，请稍后重试')
            Toast.show '向服务器保存手势失败，请稍后重试'
        .always ->
        $scope.goBack()
        GestureService.stopReject()
        $state.go 'gesture-password'
      else
        Toast.show '重设失败, 请检查你的密码'
    .always ->
      $rootScope.$broadcast("loading:hide");

  $scope.$on '$ionicView.enter', (event)->
    $scope.current_account = furion.storage.account()
    $scope.error = false

  $scope.lock = new PatternLock('#lockPatternLogin',
    margin: document.documentElement.clientWidth / 17,
    radius: document.documentElement.clientWidth / 12,
    onDraw:(pattern)->
      console.log("DRAWING")
      if ($scope.log_pattern)
        gcp = GestureService.checkPattern(pattern)
        gcp.success((data) ->
          $scope.lock.reset()
          $scope.error = false
          prev_url = window.localStorage.getItem('rt-gesture_prev_url')
          Toast.show '手势验证成功'
          if !prev_url || prev_url == '#/welcome'
            prev_url = 'app.home'
            console.log("SUCCESS gesture check, going to previous url:" + prev_url)
            $state.go(prev_url)
          else
            console.log("SUCCESS gesture check, going to previous url:" + prev_url)
            window.localStorage.removeItem('rt-gesture_prev_url')
            window.location.assign prev_url
          ).error((data) ->
            console.log("failed gesture check")
            $scope.lock.error()
            $scope.error = true
            $scope.lock.reset()
            setTimeout ->
              $scope.$apply ->
                $scope.error = false
            , 800
          )
      else
        console.log("re-gesture check")
        GestureService.setPattern(pattern)
        $scope.lock.reset()
        $scope.log_pattern = GestureService.getPattern()
        $scope.$apply()
  )# $scope.lock

  return